package com.gps.web.action.sheets;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.gps.web.comm.Unility;
import com.gps.web.comm.action.BaseSheetAction;
import com.gps.web.dao.sheet.ContactDao;
import com.gps.web.entity.sheets.Contact;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xssf.usermodel.*;
import org.apache.struts2.ServletActionContext;

public class AddressBookAction extends BaseSheetAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Resource
	private ContactDao contactDao;

	static Logger logger = Logger.getLogger(AddressBookAction.class.getName());

	private String fullName; //姓名
	private String phone; //联系电话
	private String workUnit; //所属单位
	private List<Contact> contactList;

	public String execute() throws IOException, InvalidFormatException {
		contactList = contactDao.findAll();

		return SUCCESS;
	}
	
	public String search() {
		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("fullName", fullName);
		conditions.put("phone", phone);
		conditions.put("workUnit", workUnit);
		
		contactList = contactDao.getContactByPage(conditions);
		
		return SUCCESS;
	}

	public String uploadSheet() throws Exception {
		if(StringUtils.isBlank(spreadSheetFileName)) {
			setOutMessage("请选择要上传的文件！");
			return INPUT;
		}
		if(!spreadSheetFileName.endsWith(".xls") && !spreadSheetFileName.endsWith(".xlsx")) {
			setOutMessage("文件格式错误，请上传.xls或.xlsx为后缀的excel文件！");
			return INPUT;
		}
		
		String filePath = ServletActionContext.getServletContext().getRealPath(
				com.gps.web.comm.GlobalConstants.UPLOAD_PATH
						+ spreadSheetFileName);

		SaveFile(filePath);

		if(!validateFileData(filePath)) return INPUT;

		List<Contact> ctList = new ArrayList<Contact>();

		ReadDataToBuildEntity(ctList, filePath);

		SaveRecords(ctList);

		contactList = contactDao.findAll();

		return SUCCESS;
	}

	@Override
	protected void initSheetHeader() {
		colHeaderList.add(new ColumnHeader("姓名"));
		colHeaderList.add(new ColumnHeader("联系电话"));
		colHeaderList.add(new ColumnHeader("所属单位"));
		colHeaderList.add(new ColumnHeader("身份"));
		colHeaderList.add(new ColumnHeader("备注"));
	}

	private void SaveFile(String filePath) throws Exception {
		try {
			if (spreadSheet != null) {
				File destFile = new File(filePath);
				Unility.UploadFile(spreadSheet, destFile);
			}
		} catch (Exception e) {
			throw e;
		}
	}

	private boolean validateFileData(String filePath)
			throws FileNotFoundException {
		
		InputStream inp = new FileInputStream(filePath);
		XSSFWorkbook wb;
		try {
			wb = new XSSFWorkbook(inp);
		} catch (Exception e) {
			setOutMessage("文件读取失败，请重新上传！");
			return false;
		}
		XSSFSheet sheet = wb.getSheetAt(0);
		if(sheet == null || sheet.getRow(0) == null){
			setOutMessage("文件内容为空，请重新上传！");
			return false;
		}
		if(!validateSheetHeader(sheet.getRow(0))){
			setOutMessage("文件标题列格式错误，请重新上传！");
			return false;
		}
		
		return true;
	}

	private void ReadDataToBuildEntity(List<Contact> ctList, String filePath)
			throws FileNotFoundException {
		InputStream inp = new FileInputStream(filePath);
		XSSFWorkbook wb;
		try {
			wb = new XSSFWorkbook(inp);
		} catch (Exception e) {
			return;
		}
		XSSFSheet sheet = wb.getSheetAt(0);
		// 循环行Row
		for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
			try {
				XSSFRow row = sheet.getRow(rowNum);
				if (row == null) {
					continue;
				}

				Contact ct = new Contact();
				// 循环列Cell
				for (int cellNum = 0; cellNum <= row.getLastCellNum(); cellNum++) {
					XSSFCell cell = row.getCell(cellNum);
					if (cell == null) {
						continue;
					}
					switch (cellNum) {
					case 0:
						ct.setFullName(getValue(cell));
						break;
					case 1:
						ct.setPhone(getValue(cell));
						break;
					case 2:
						ct.setWorkUnit(getValue(cell));
						break;
					case 3:
						ct.setPosition(getValue(cell));
						break;
					case 4:
						ct.setRemarks(getValue(cell));
						break;
					default:
						break;
					}
				}
				ctList.add(ct);
			} catch (Exception e) {
			}
		}
	}

	private Boolean SaveRecords(List<Contact> gdList) {
		for (int i = 0; i < gdList.size(); i++) {
			contactDao.saveOrUpdate(gdList.get(i));
		}
		return true;
	}

	private String getValue(XSSFCell cell) {
		if (cell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {
			return String.valueOf(cell.getBooleanCellValue());
		} else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
			return new DecimalFormat("#.##").format(cell.getNumericCellValue());
		} else if (cell.getCellType() == XSSFCell.CELL_TYPE_FORMULA) {
			return cell.getCellFormula();
		} else if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
			return cell.getStringCellValue();
		} else {
			return cell.toString();
		}
	}

	
	public String getFullName() {
		return fullName;
	}

	public void setFullName(String fullName) {
		this.fullName = fullName;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getWorkUnit() {
		return workUnit;
	}

	public void setWorkUnit(String workUnit) {
		this.workUnit = workUnit;
	}

	public List<Contact> getContactList() {
		return contactList;
	}

	public void setContactList(List<Contact> contactList) {
		this.contactList = contactList;
	}

}
